package com.adnaan.backend.service.storage;

import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.config.StorageConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service("aliyunStorageService")
public class AliyunStorageService implements StorageService {
    private final StorageConfig storageConfig;
    private final String bucket;
    private final String endpoint;
    private final String domain;
    private final String accessKeyId;
    private final String accessKeySecret;

    public AliyunStorageService(StorageConfig storageConfig) {
        this.storageConfig = storageConfig;
        StorageConfig.Aliyun aliyun = storageConfig.getAliyun();
        this.bucket = aliyun.getBucket();
        this.endpoint = aliyun.getEndpoint();
        this.domain = aliyun.getDomain();
        this.accessKeyId = aliyun.getAccessKeyId();
        this.accessKeySecret = aliyun.getAccessKeySecret();
    }

    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new ServicesException("上传文件为空");
        }
        String fileName = getFileName(file.getOriginalFilename());
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(getContentType(fileName));
            ossClient.putObject(bucket, fileName, file.getInputStream(), metadata);
            return fileName;
        } catch (IOException e) {
            log.error("阿里云OSS文件上传失败", e);
            throw new ServicesException("文件上传失败");
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public void delete(String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.deleteObject(bucket, fileName);
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public String getUrl(String fileName) {
        return domain + '/' + fileName;
    }

    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }

    private String getContentType(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return switch (suffix.toLowerCase()) {
            case "png" -> "image/png";
            case "jpg", "jpeg" -> "image/jpeg";
            case "gif" -> "image/gif";
            case "mp4" -> "video/mp4";
            default -> "application/octet-stream";
        };
    }
} 